package jam4j.lang;

import jam4j.OutputChannel;
import jam4j.util.Strings;

import java.util.*;

final class Scope extends HashMap<String, String[]> {
    Scope() { }
    Scope(Map<String, String[]> m) {
        super(m);
    }
    
    @Override 
    public String[] get(Object key) {
        final String[] ans = super.get(key);
        if (ans != null)
            OutputChannel.VAR_GET.printf("get %s = %s\n",
                    key, Strings.rightJoiner(" ", (Object[]) ans));
        return ans;
    }
    
    @Override
    public String[] put(String key, String[] value) {
        OutputChannel.VAR_SET.printf("set %s = %s\n",
                    key, Strings.rightJoiner(" ", (Object[]) value));
        return super.put(key, value);
    }
    
    void set(String key, String ... values) {
        put(key, values);
    }
    
    void setAppend(String key, String ... values) {
        final String[] oldValues = get(key);
        if (oldValues == null)
            put(key, values);
        else {
            final String[] newValues =
                Arrays.copyOf(oldValues, oldValues.length + values.length);
            
            System.arraycopy(
                    values, 0, newValues, oldValues.length, values.length);
            put(key, newValues);
        }
    }
    
    void setDefault(String key, String ... values) {
        if (!containsKey(key))
            put(key, values);
    }
    
    boolean isLocal(String name) {
        return containsKey(name);
    }
    
    void makeLocal(String name) {
        put(name, null);
    }
    
    @Override
    public String toString() {
        if (isEmpty())
            return "{}";
        
        final StringBuilder builder = new StringBuilder("{");
        for (Map.Entry<String, String[]> entry : entrySet())
            builder.append(entry.getKey()).append('=')
                .append(Arrays.toString(entry.getValue()))
                .append(',');
        builder.setCharAt(builder.length() - 1, '}');
        return builder.toString();
    }
}
